﻿using System.Collections.Generic;
using System.Windows.Forms;
using csvm.coordinator.contract;
using csvm.datamodel.contract;
using WinFormsHost;

namespace csvm.portal
{
  public partial class UI : Form, IEntryPoint
  {
    private readonly ICoordinator _coordinator;

    public UI(ICoordinator coordinator)
    {
      _coordinator = coordinator;
      _coordinator.OnProgressChanged += _coordinator_OnProgressChanged;
      InitializeComponent();
    }

    void _coordinator_OnProgressChanged(double obj)
    {
      this.progressBarFileLoadProgress.Value = (int)obj;
    }

    public Form MainForm
    {
      get { return this; }
    }

    private void buttonLoadFile_Click(object sender, System.EventArgs e)
    {
      var openFileDialog = new OpenFileDialog();
      openFileDialog.CheckFileExists = true;
      if (openFileDialog.ShowDialog() != DialogResult.OK)
        return;

      var filename = openFileDialog.FileName;

      Record header;
      var pages = _coordinator.LoadPages(filename, out header);

      ClearListView();

      FillHeader(header);

      FillData(pages);
    }

    private void FillData(IEnumerable<Page> pages)
    {
      foreach (var page in pages)
      {
        FillPage(page);

      }
    }

    private void FillPage(Page page)
    {
      foreach (var record in page.Records)
      {
        FillRecord(record);
      }
    }

    private void FillRecord(Record record)
    {
      var listViewItem = new ListViewItem();
      var isFirstItem = true;
      foreach (var item in record.Values)
      {
        if (isFirstItem)
          listViewItem.Text = item;
        else
          listViewItem.SubItems.Add(item);
        isFirstItem = false;
      }
      this.listViewCsvData.Items.Add(listViewItem);
    }

    private void ClearListView()
    {
      this.listViewCsvData.Items.Clear();
      this.listViewCsvData.Columns.Clear();
    }

    private void FillHeader(Record header)
    {
      foreach (var item in header.Values)
      {
        this.listViewCsvData.Columns.Add(item);
      }
    }
  }
}
